//
//  FontTableViewController.m
//  iOSStudy
//
//  Created by Evan Xie on 9/7/15.
//  Copyright (c) 2015 Family Wings. All rights reserved.
//

#import "FontTableViewController.h"


static NSString *FontFamilyKey      = @"FontFamilyKey";
static NSString *FontsInFamilyKey   = @"FontsInFamilyKey";


@interface FontTableViewController ()
{
    NSMutableArray *_allSupportedFontFamilies;
    
    UITableView *_fontTableView;
}

@end

@implementation FontTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _allSupportedFontFamilies = [NSMutableArray arrayWithCapacity:0];
    
    NSArray *fontFamilies = [UIFont familyNames];
    for (NSString *familyName in fontFamilies) {
        NSArray *fontsInFamily = [UIFont fontNamesForFamilyName:familyName];
        NSDictionary *fontInfo = @{ FontFamilyKey: familyName, FontsInFamilyKey: fontsInFamily };
        [_allSupportedFontFamilies addObject:fontInfo];
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return _allSupportedFontFamilies.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    // Return the number of rows in the section.
    NSDictionary *fontInfo = _allSupportedFontFamilies[section];
    
    return [fontInfo[FontsInFamilyKey] count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSDictionary *fontInfo = _allSupportedFontFamilies[section];
    return fontInfo[FontFamilyKey];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FontTableCell"];
    
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"FontTableCell"];
        cell.detailTextLabel.font = [UIFont systemFontOfSize:16.0];
        cell.detailTextLabel.textColor = [UIColor magentaColor];
    }
    
    NSDictionary *fontInfo = _allSupportedFontFamilies[indexPath.section];
    NSArray *fontNames = fontInfo[FontsInFamilyKey];
    
    cell.textLabel.font = [UIFont fontWithName:fontNames[indexPath.row] size:16.0];
    cell.textLabel.text = fontNames[indexPath.row];
    
    cell.detailTextLabel.text = fontNames[indexPath.row];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
@end
